/* eslint-disable indent */
/* eslint-disable semi */
const formidable = require('formidable');
const _express = require('express');
const express = _express();
const user = require('./models/userDetail');
const menus = require('./models/menu')
const points = require('./models/point')
const uuid = require('uuid');
var cors = require('cors');
const path = require('path')

// 全局配置
express.use(cors());
express.use(_express.static(path.resolve(__dirname, '../dist')))

const jwt = require('jsonwebtoken')
const { secretKey } =require('./token/constant')  //提取Token加密内容 ,见下
// 全局验证Token是否合法
const jwtAuth = require('./token/index')  //验证Token配置文件,见下
express.use(jwtAuth);
// 路由中间件
express.use((err, req, res, next) => {
    if(err && err.name !== 'UnauthorizedError'){
        res.status(401).send('登录信息失效');
        return;
    } else {   
        // 任何路由信息都会执行这里面的语句
        var token = '';
        if(req.get('Authorization')){
            token = req.get('Authorization').match(/Bearer\s(.*?),/)
        }
        if(token){
            try{
                var info = jwt.verify(token[1].trim(), secretKey);
            }catch(err){
                res.status(401).send('登录信息失效');
                return;
            }
        } else {
            res.status(401).send('非法token');
            return;
        }
    }
    
    // if (err.name === 'UnauthorizedError') {   
    //     //  这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
    //     // res.status(401).send('非法token');
    // }
    // 把它交给下一个中间件，注意中间件的注册顺序是按序执行
    next();
});

const studentListInDay = require('./routes/studentListInDay')
express.use('/api/studentListInDay', studentListInDay)

const delete_note = require('./routes/delete_note')
express.use('/api/delete_note', delete_note)

const bind_email = require('./routes/bind_email')
express.use('/api/bind_email', bind_email)

const verify_signin = require('./routes/verify_signin')
express.use('/api/verify_signin', verify_signin)

const add_logs = require('./routes/add_logs')
express.use('/api/add_logs', add_logs)

const update_demo = require('./routes/update_demo')
express.use('/api/update_demo', update_demo)

const get_demo = require('./routes/get_demo')
express.use('/api/get_demo', get_demo)

const get_demos = require('./routes/get_demos')
express.use('/api/get_demos', get_demos)

const add_demo = require('./routes/add_demo')
express.use('/api/add_demo', add_demo)

const changeAvatar = require('./routes/changeAvatar')
express.use('/api/changeAvatar', changeAvatar)

const get_index_homework = require('./routes/get_index_homework')
express.use('/api/get_index_homework', get_index_homework)

const getCollectionFlags = require('./routes/getCollectionFlags')
express.use('/api/getCollectionFlags', getCollectionFlags)

const getQuestionAnswer = require('./routes/getQuestionAnswer')
express.use('/api/getQuestionAnswer', getQuestionAnswer)

const getAllQuestions = require('./routes/getAllQuestions')
express.use('/api/getAllQuestions', getAllQuestions)

const get_onePoint = require('./routes/get_onePoint')
express.use('/api/get_onePoint', get_onePoint)

const addDemoCode = require('./routes/addDemoCode')
express.use('/api/addDemoCode', addDemoCode)

const getLearnPath = require('./routes/getLearnPath')
express.use('/api/getLearnPath', getLearnPath)

const add_learnpath = require('./routes/add_learnpath')
express.use('/api/add_learnpath', add_learnpath)

const homeworkNot = require('./routes/homeworkNot')
express.use('/api/homeworkNot', homeworkNot)

const normalHomeworkHandeyet = require('./routes/normalHomeworkHandeyet')
express.use('/api/normalHomeworkHandeyet', normalHomeworkHandeyet)

const workDetail = require('./routes/workDetail')
express.use('/api/workDetail', workDetail)

const workAnalysisPerson = require('./routes/workAnalysisPerson')
express.use('/api/workAnalysisPerson', workAnalysisPerson)

const workAnalysisTotal = require('./routes/workAnalysisTotal')
express.use('/api/workAnalysisTotal', workAnalysisTotal)

const getPointAllQuestion = require('./routes/getPointAllQuestion')
express.use('/api/getPointAllQuestion', getPointAllQuestion)

const refindPassword = require('./routes/refindPassword')
express.use('/api/refindPassword', refindPassword)

const deletePosting = require('./routes/deletePosting')
express.use('/api/deletePosting', deletePosting)

const codingAnalysis = require('./routes/codingAnalysis')
express.use('/api/codingAnalysis', codingAnalysis)

const getAllFeedback = require('./routes/getAllFeedback')
express.use('/api/getAllFeedback', getAllFeedback)

const addOneConnect = require('./routes/addOneConnect')
express.use('/api/addOneConnect', addOneConnect)

const getAllAssistantsWork = require('./routes/getAllAssistantsWork')
express.use('/api/getAllAssistantsWork', getAllAssistantsWork)

const getAllRecord = require('./routes/getAllRecord')
express.use('/api/getAllRecord', getAllRecord)

const getAllProcess = require('./routes/getAllProcess')
express.use('/api/getAllProcess', getAllProcess)

const saveCodeRecord = require('./routes/saveCodeRecord')
express.use('/api/saveCodeRecord', saveCodeRecord)

const getPostings = require('./routes/getPostings')
express.use('/api/getPostings', getPostings)

const addOnePosting = require('./routes/addOnePosting')
express.use('/api/addOnePosting', addOnePosting)

const getErroredQuestion = require('./routes/getErroredQuestion')
express.use('/api/getErroredQuestion', getErroredQuestion)

const getCollectedQuestionIs = require('./routes/getCollectedQuestionIs')
express.use('/api/getCollectedQuestionIs', getCollectedQuestionIs)

const getCollectedQuestion = require('./routes/getCollectedQuestion')
express.use('/api/getCollectedQuestion', getCollectedQuestion)

const collectQuestion = require('./routes/collectQuestion')
express.use('/api/collectQuestion', collectQuestion)

const getOneQuestion = require('./routes/getOneQuestion')
express.use('/api/getOneQuestion', getOneQuestion)

const uploadExcel = require('./routes/uploadExcel')
express.use('/api/uploadExcel', uploadExcel)

const getExcel = require('./routes/getExcel')
express.use('/api/getExcel', getExcel)

const getworkAnalysisExcel = require('./routes/getworkAnalysisExcel')
express.use('/api/getworkAnalysisExcel', getworkAnalysisExcel)

const uploadImg = require('./routes/uploadImg')
express.use('/api/uploadImg', uploadImg)

const getImg = require('./routes/getImg')
express.use('/api/getImg', getImg)

const savePoint = require('./routes/savePoint')
express.use('/api/savePoint', savePoint)

const modifyPoint = require('./routes/modifyPoint')
express.use('/api/modifyPoint', modifyPoint)

const deletePoint = require('./routes/deletePoint')
express.use('/api/deletePoint', deletePoint)

const addQuestion = require('./routes/addQuestion')
express.use('/api/addQuestion', addQuestion)

const queryQuestion = require('./routes/queryQuestion')
express.use('/api/queryQuestion', queryQuestion)

const modifyQuestion = require('./routes/modifyQuestion')
express.use('/api/modifyQuestion', modifyQuestion)

const deleteQuestion = require('./routes/deleteQuestion')
express.use('/api/deleteQuestion', deleteQuestion)

const handleApply = require('./routes/handleApply')
express.use('/api/handleApply', handleApply)

const addApply = require('./routes/addApply')
express.use('/api/addApply', addApply)

const getApply = require('./routes/getApply')
express.use('/api/getApply', getApply)

const getMessage = require('./routes/getMessage')
express.use('/api/getMessage', getMessage)

const restoreTrash = require('./routes/restoreTrash')
express.use('/api/restoreTrash', restoreTrash)

const removeReaded = require('./routes/removeReaded')
express.use('/api/removeReaded', removeReaded)

const hasRead = require('./routes/hasRead')
express.use('/api/hasRead', hasRead)

const getUnreadNumber = require('./routes/getUnreadNumber')
express.use('/api/getUnreadNumber', getUnreadNumber)

const appoint = require('./routes/appoint')
express.use('/api/appoint', appoint)

const findOneUser = require('./routes/findOneUser')
express.use('/api/findOneUser', findOneUser)

const add_record = require('./routes/add_record')
express.use('/api/add_record', add_record)

const get_learnProcess = require('./routes/getLearnProcess')
express.use('/api/getlearn_process', get_learnProcess)

const add_PointProcess = require('./routes/add_PointProcess')
express.use('/api/add_PointProcess', add_PointProcess)

const getProcess = require('./routes/getProcess')
express.use('/api/get_process', getProcess)

const getSingleRecond = require('./routes/getSingleRecord')
express.use('/api/getSingleRecord', getSingleRecond)

const addMessage = require('./routes/addMessage')
express.use('/api/addMessage', addMessage)

const getPointContent = require('./routes/getPointContent')
express.use('/api/getPointContent', getPointContent)

const getQuestionContent = require('./routes/getQuestionContent')
express.use('/api/getQuestionContent', getQuestionContent)

const addHomework = require('./routes/addHomework')
express.use('/api/addHomework', addHomework)

const getHomework = require('./routes/getHomework')
express.use('/api/getHomework', getHomework)

const add_workRecord =require('./routes/add_workRecord')
express.use('/api/add_workRecord', add_workRecord)

const getQuestionList = require('./routes/getQuestionList')
express.use('/api/getQuestionList', getQuestionList)

const getQandAlist = require('./routes/getQandAlist')
express.use('/api/getQandAlist', getQandAlist)

const getQuesPath = require('./routes/getQuesPath')
express.use('/api/getQuesPath', getQuesPath)

const getCreateLearnPath = require('./routes/getCreateLearnPath')
express.use('/api/getCreateLearnPath', getCreateLearnPath)

const deleteLearnPath = require('./routes/deleteLearnPath')
express.use('/api/deleteLearnPath', deleteLearnPath)

const updateLearnPath = require('./routes/updateLearnPath')
express.use('/api/updateLearnPath', updateLearnPath)

const getCodeList = require('./routes/getCodeList')
express.use('/api/getCodeList', getCodeList)

const getCode = require('./routes/getCode')
express.use('/api/getCode', getCode)

const getLearnNumbyDay = require('./routes/getLearnNumbyDay')
express.use('/api/getLearnNumbyDay', getLearnNumbyDay)

const getQuesNumbyDay = require('./routes/getQuesNumbyDay')
express.use('/api/getQuesNumbyDay', getQuesNumbyDay)

const getWorkNumbyDay = require('./routes/getWorkNumbyDay')
express.use('/api/getWorkNumbyDay', getWorkNumbyDay)

const getCodeNumbyDay = require('./routes/getCodeNumbyDay')
express.use('/api/getCodeNumbyDay', getCodeNumbyDay)

const getLastCode = require('./routes/getLastCode')
express.use('/api/getLastCode', getLastCode)

const add_codeidea = require('./routes/add_codeidea')
express.use('/api/add_codeidea', add_codeidea)

const get_codeideas = require('./routes/get_codeideas')
express.use('/api/get_codeideas', get_codeideas)

const add_guide = require('./routes/add_guide')
express.use('/api/add_guide', add_guide)

const add_codeCollection = require('./routes/add_codeCollection')
express.use('/api/add_codeCollection', add_codeCollection)

const get_allCodeCollection = require('./routes/get_allCodeCollection')
express.use('/api/get_allCodeCollection', get_allCodeCollection)

const get_codeCollected = require('./routes/get_codeCollected')
express.use('/api/get_codeCollected', get_codeCollected)

const del_codeCollection = require('./routes/del_codeCollection')
express.use('/api/del_codeCollection', del_codeCollection)

const update_codeidea = require('./routes/update_codeidea')
express.use('/api/update_codeidea', update_codeidea)

const update_codeideas = require('./routes/update_codeideas')
express.use('/api/update_codeideas', update_codeideas)

const save_audio = require('./routes/save_audio')
express.use('/api/save_audio', save_audio)

const merge_audio = require('./routes/merge_audio')
express.use('/api/merge_audio', merge_audio)

const get_audio = require('./routes/get_audio')
express.use('/api/get_audio', get_audio)

const add_customidea = require('./routes/add_customidea')
express.use('/api/add_customidea', add_customidea)

const get_codeideaByFlag = require('./routes/get_codeideaByFlag')
express.use('/api/get_codeideaByFlag', get_codeideaByFlag)

const get_customidea = require('./routes/get_customidea')
express.use('/api/get_customidea', get_customidea)

const get_wordviewFlag = require('./routes/get_wordviewFlag')
express.use('/api/get_wordviewFlag', get_wordviewFlag)

const add_wordviewFlag = require('./routes/add_wordviewFlag')
express.use('/api/add_wordviewFlag', add_wordviewFlag)

const update_workRecord = require('./routes/update_workRecord')
express.use('/api/update_workRecord', update_workRecord)

const saveMorePoints = require('./routes/saveMorePoints')
express.use('/api/saveMorePoints', saveMorePoints)

const modifyMorePoints = require('./routes/modifyMorePoints')
express.use('/api/modifyMorePoints', modifyMorePoints)

const delMorePoints = require('./routes/delMorePoints')
express.use('/api/delMorePoints', delMorePoints)

const getMorePoints = require('./routes/getMorePoints')
express.use('/api/getMorePoints',getMorePoints)

const add_note = require('./routes/add_note')
express.use('/api/add_note',add_note)

const get_notes = require('./routes/get_notes')
express.use('/api/get_notes',get_notes)

const like_and_cancel = require('./routes/like_and_cancel')
express.use('/api/like_and_cancel',like_and_cancel)

const process = require('./routes/process');
express.use('/api/process', process);

const project = require('./routes/project');
express.use('/api/project', project);

express.post('/api/getContent', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            points.find({
                menu: fields.menu
            }, null, { sort: [[['_id', 1]]] }, (err, docs) => {
                if (err) {
                    res.json({ 'state': false, 'msg': err });
                } else {
                    // console.log(key)
                    res.json({ 'state': true, 'result': docs });
                }
            })

        }

    });
})

express.post('/api/getMenu', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            let findMenu = () => {
                return new Promise(function (resolve, reject) {
                    if (fields.lesson === 'all') {
                        menus.find({}, {
                            _id: 0
                        }, (err, key) => {
                            if (err) {
                                res.json({ 'state': false, 'msg': err });
                            } else {
                                // res.json({ 'state': true, 'result': key });
                                resolve(key)
                            }
                        })
                    } else {
                        menus.findOne({
                            lesson: fields.lesson
                        }, {
                            _id: 0,
                            menu: 1
                        }, (err, key) => {
                            if (err) {
                                res.json({ 'state': false, 'msg': err });
                            } else {
                                // console.log(key)
                                // res.json({ 'state': true, 'result': key });
                                resolve(key)
                            }
                        })
                    }
                })

            }


            var findProgress = (key) => {
                let user = require("./models/userDetail")
                user.findOne({
                    UUID: fields.UUID
                }, {
                    _id: 0,
                    process: 1
                }, function (err, doc) {
                    if (err) {
                        res.json({ 'state': false, 'msg': err });
                    } else {
                        res.json({ 'state': true, 'result': key, 'process': doc });
                    }
                })
            }

            findMenu().then(findProgress)
        }
    });
})

express.post('/api/duplicatUsername', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        }
        user.find({ 'username': fields.username })
            .then(users => {
                if (users.length && fields.UUID!==users[0].UUID) {
                    res.json({ 'state': true, 'duplicate': true });
                } else {
                    res.json({ 'state': false, 'duplicate': false });
                }
            }).catch(err => {
                console.log(err);
                res.json({ 'state': false });
            });
    });
});
express.post('/api/duplicatStuNo', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        }
        user.find({ 
            'stuNo': fields.stuNo,
            'school': fields.school
        })
            .then(users => {
                if (users.length && fields.UUID!==users[0].UUID) {
                    res.json({ 'state': true, 'duplicate': true });
                } else {
                    res.json({ 'state': true, 'duplicate': false });
                }
            }).catch(err => {
                console.log(err);
                res.json({ 'state': false , 'msg': '学号重复验证出错！'});
            });
    });
});
express.post('/api/supplyDetail', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            try {
                const verifyCode = require("./models/verifyCode")
    
                let res_veri = await verifyCode.find({
                    code: fields.verifycode,
                    email: fields.email
                })
                if(res_veri.length>0){
                    let UUID = uuid.v1();
                    await user.create({
                        'UUID': UUID,
                        'realName': fields.realName,
                        'sex': "",
                        'school': fields.school,
                        'stuNo': fields.stuNo,
                        'username': fields.username,
                        'password': fields.password,
                        'userGroup': '0',
                        'flags': [],
                        'process': [["js,-1,-1", -1, ""], ["wx,-1,-1", -1, ""], ["ydhlw,-1,-1", -1, ""]],
                        'email': fields.email,
                        'avatar': '头像3.svg',
                        'time': +new Date()
                    })
                    await verifyCode.deleteMany({email: fields.email})
                    res.json({ 'state': true })
                } else {
                    res.json({
                        state: false,
                        msg: '验证码错误！'
                    })
                }

            } catch(err) {
                console.log(err)
                res.json({
                    state: false,
                    msg: '注册失败'
                })
            }
            
        }
    });
});
express.post('/api/modifyUserDetail', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            try {
                const verifyCode = require("./models/verifyCode")
                let res_veri = await verifyCode.find({
                    code: fields.code,
                    email: fields.email
                })
                if(res_veri.length>0){
                    let user_res = await user.findOneAndUpdate({ 'UUID': fields.UUID }, {
                        $set: {
                            realName: fields.realName,
                            username: fields.username,
                            school: fields.school,
                            stuNo: fields.stuNo,
                            email: fields.email
                        }
                    }, { new: true })
                    await verifyCode.deleteMany({email: fields.email})
                    res.json({ 'state': true, 'user': user_res });
                } else {
                    res.json({
                        state: false,
                        msg: '验证码错误！'
                    })
                }

            } catch(err) {
                console.log(err)
                res.json({
                    state: false,
                    msg: '修改用户信息出错'
                })
            }
            
        }
    });
});
express.post('/api/getUserDetail', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            user.findOne({ 
                'UUID': fields.UUID 
            }).then(userDetail => {
                if(userDetail.email == null){
                    let result = {
                        username: userDetail.username,
                        realName: userDetail.realName,
                        school: userDetail.school,
                        stuNo:  userDetail.stuNo,
                        email: "",
                        avatar: userDetail.avatar || '头像3.svg'
                    }
                    console.log(result);
                    res.json(result);
                }else {
                    let result = {
                        username: userDetail.username,
                        realName: userDetail.realName,
                        school: userDetail.school,
                        stuNo:  userDetail.stuNo,
                        email: userDetail.email,
                        avatar: userDetail.avatar || '头像3.svg'
                    }
                    res.json(result);
                }
            }).catch((err) => {
                res.json(err);
            });
        }
    });
});
express.post('/api/loginUserPass', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } 
        user.findOne({ 'username': fields.username }, { _id: 0, __v: 0 }).then((userpass) => {
            if (!!userpass) {
                if (userpass.password === fields.password) {
                    let temp = JSON.parse(JSON.stringify(userpass))
                    if(!temp.avatar) {
                        temp = {...temp, avatar: "头像3.svg"}
                    }
                    delete temp.password
                    let tokenObj={   //携带参数
                        password: userpass.password,
                        username: userpass.username
                    }
                    let token = jwt.sign(tokenObj, secretKey, {
                        expiresIn : parseInt((new Date().setHours(28, 0, 0, 0)-new Date())/1000) // 授权至本地时间 第二天凌晨四点
                    });
                    res.json({
                        user: JSON.stringify(temp),
                        'UUID': userpass.UUID,
                        'state': true,
                        token: token
                    });
                } else {
                    res.json({ 'state': false, 'msg': '密码错误！' });
                }
            } else {
                res.json({ 'state': false, 'msg': '用户名不存在！' });
            }
        }).catch((err) => {
            res.json({ 'state': false, 'msg': '登录出错！' });
        });
    });
});
express.post('/api/changePassword', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            try {
                const user_data = await user.find({
                    'UUID': fields.UUID,
                    'password': fields.oldpass
                })
                if(user_data.length===0){
                    res.json({
                        state: false,
                        msg: "密码错误！"
                    })
                    return;
                }
                await user.findOneAndUpdate({ 
                    'UUID': fields.UUID
                }, {
                    $set: {
                        password: fields.password
                    }
                }, { new: true })
                res.json({ 'state': true });
            } catch(err){
                res.json(err);
            }
        }
    });
});
express.post('/api/changeGroup', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            user.findOne({ 'UUID': fields.UUID }).then((resource) => {
                if (resource.userGroup == 3) {
                    user.findOneAndUpdate({ 'UUID': fields.targetUUID }, {
                        $set: {
                            userGroup: fields.group
                        }
                    }, { new: true }).then(() => {
                        res.json({ 'state': true });
                    });
                } else {
                    res.json({ 'state': false, 'msg': 'no previledge' });
                }
            }).catch((err) => {
                res.json(err);
            });
        }
    });
});
express.post('/api/getUserList', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            user.findOne({ 'UUID': fields.UUID }).then((resource) => {
                if (resource.userGroup == 3) {
                    user.find({}, { 'password': 0, '_id': 0 }).then((result) => {
                        res.json({ 'state': true, 'result': result });
                    });
                } else {
                    res.json({ 'state': false, 'msg': 'no previledge' });
                }
            });
        }
    });
});

module.exports = express;